<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.title" size="medium" placeholder="用户名" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />

      <el-button v-waves class="filter-item" type="primary" size="medium" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" size="medium" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>

      <div class="block">
        <el-table
          :data="tableData"
          style="width: 100%;margin-bottom: 20px;"
          row-key="id">
          <el-table-column
            prop="id"
            label="ID"
            width="80">
          </el-table-column>
          <el-table-column label="头像" width="180">
            <template slot-scope="scope">
              <el-image class="row-avatar" :src="scope.row.fullAvatar"></el-image>
            </template>
          </el-table-column>
          <el-table-column
            prop="username"
            label="用户名">
          </el-table-column>
          <el-table-column
            prop="nickname"
            label="昵称"
            width="180">
          </el-table-column>
          <el-table-column
            prop="mobile"
            label="手机号"
            width="180">
          </el-table-column>
          <el-table-column
            prop="create_time"
            label="创建时间">
          </el-table-column>
          <el-table-column label="操作" width="200">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-popconfirm confirm-button-text='好的' cancel-button-text='不用了' icon="el-icon-info" icon-color="red" title="确定删除吗？" @onConfirm="() => handleDelete(scope.$index, scope.row)">
                <el-button v-if="scope.row.username !== 'admin'" slot="reference" size="mini" type="danger">删除</el-button>
              </el-popconfirm>

            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" @close="closeDialog">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="80px" style="width: 400px; margin-left:50px;">
        <el-form-item label="用户名" prop="username">
          <el-input v-if="dialogStatus === 'update' && temp.username === 'admin'" v-model="temp.username" :disabled="true" type="text" placeholder="请输入用户名" maxlength="50" />
          <el-input v-else v-model="temp.username" type="text" placeholder="请输入用户名" maxlength="50" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="temp.nickname" type="text" placeholder="请输入昵称" maxlength="50" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="temp.mobile" type="text" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" type="text" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" placeholder="" min="6" show-password />
        </el-form-item>
        <el-form-item v-if="temp.username !== 'admin'" label="角色" prop="password">
          <template>
            <el-select v-model="temp.roles" multiple placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.display_name"
                :value="item.id">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadUri"
            :data="uploadData"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="temp.avatar" :src="avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          保存
        </el-button>
      </div>
    </el-dialog>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { addManage, deleteManage, getManageList, updateManage } from '@/api/user'
import { getRoutes } from '@/api/role'
export default {
  name: 'Manage',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        title: undefined,
        type: undefined
      },
      tableData: [],
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogStatus: '',
      dialogFormVisible: false,
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        nickname: [{ required: true, message: '昵称不能为空', trigger: 'blur' }],
        mobile: [{ required: true, message: '手机号不能为空', trigger: 'blur' }]
      },
      temp: {
        id: undefined,
        mobile: '',
        username: '',
        email: '',
        nickname: '',
        avatar: '',
        password: '',
        roles: []
      },
      uploadUri: '',
      uploadData: { type: 'admin_avatar' },
      avatar: '',
      rolesList: []
    }
  },
  created() {
    this.getList()
    this.uploadUri = process.env.VUE_APP_BASE_API_HOST + '/common/upload-to-local'
    this.getRolesList()
  },
  methods: {
    getList() {
      getManageList(this.listQuery).then(response => {
        if (response.code === 200) {
          this.tableData = response.data.rows
          this.total = response.data.total
        }
        this.resetTemp()
      })
    },
    getRolesList() {
      getRoutes({ page: 1, limit: 9999 }).then(response => {
        if (response.code === 200) {
          this.rolesList = response.data.rows
        }
      })
    },
    handleFilter() {
      this.getList()
    },
    resetTemp() {
      this.cascader_val = []
      this.temp = {
        id: undefined,
        mobile: '',
        username: '',
        email: '',
        nickname: '',
        avatar: '',
        password: '',
        roles: []
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleEdit(index, row) {
      this.temp = {
        id: row.id,
        mobile: row.mobile,
        username: row.username,
        email: row.email,
        nickname: row.nickname,
        avatar: row.avatar,
        password: '',
        roles: row.roles
      }
      this.avatar = row.fullAvatar
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDelete(index, row) {
      deleteManage(row.id).then(response => {
        if (response.code === 200) {
          this.$message({
            message: response.msg,
            type: 'success'
          })
          this.dialogFormVisible = false
          this.getList()
        }
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          console.log(this.temp)
          addManage(this.temp).then(response => {
            if (response.code === 200) {
              this.$message({
                message: response.msg,
                type: 'success'
              })
              this.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateManage(this.temp).then(response => {
            if (response.code === 200) {
              this.$message({
                message: response.msg,
                type: 'success'
              })
              this.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },
    closeDialog() {
      this.resetTemp()
    },
    handleAvatarSuccess(res, file) {
      if (res.code !== 200) {
        this.$message.error(res.msg)
      }
      this.avatar = URL.createObjectURL(file.raw)
      this.temp.avatar = res.data.pic
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isLt2M
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
  border: 1px solid #8c939d;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.row-avatar{
  width: 78px;
  height: 78px;
  display: block;
  border-radius: 50%;
}
</style>
